package com.sockety2;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import static java.lang.System.out;

public class Server extends Thread {
	public static int connSocketId=0;
	public static int serverId=0;
	
	public boolean run;
	
	private ServerSocket ss;
	private ArrayList<ThrSocket2> clientsSockets = new ArrayList<ThrSocket2>();
	private int port;
	private int timeout;
	
	public Server (int port , int timeout, String name ){
		this(port, timeout);
		this.setName(name);
	}
	public Server (int port , int timeout ){
		serverId++;
		this.port = port;
		this.timeout = timeout;
	}
	
	@Override
	public void run() {
		
		try {
			ss = new ServerSocket(port);
			ss.setSoTimeout(timeout);
			run = true;
			out.println("Server " +this.getName()+" started. Listening on port " + String.valueOf(port));
			while(true){
				Socket incoming = null;
	        	try {
	        		incoming = ss.accept();
	        		
	        		ThrSocket2 ths = new ThrSocket2(incoming, this);
	        		clientsSockets.add(ths);
	                
	        		ths.setName("Server" + serverId + " thr " + connSocketId++);
	        		ths.start();
	        		
	        		
				} catch (SocketTimeoutException ste) {
					if(!run){kill();break;}
				}	
			 }
			
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void kill(){
		run = false;
		
		for (ThrSocket2 cliSocket : clientsSockets) {
			if(cliSocket != null){
				cliSocket.run = false;
			}
		}
	}
	
}
